// 用户状态管理 - Pinia Store
import { defineStore } from 'pinia';
import { ref, computed } from 'vue';
import type { UserInfo } from '@/types';

/**
 * 用户 Store - 使用 Composition API 风格
 */
export const useUserStore = defineStore('user', () => {
  // 状态
  const userInfo = ref<UserInfo | null>(null);
  const isLoading = ref(false);

  // 计算属性
  const isLoggedIn = computed(() => {
    if (!userInfo.value) return false;

    // 检查 token 是否过期
    try {
      const token = uni.getStorageSync('token');
      const expiresAt = uni.getStorageSync('expiresAt');

      if (!token || !expiresAt) return false;
      return Date.now() < expiresAt;
    } catch {
      return false;
    }
  });

  const avatar = computed(() => {
    return userInfo.value?.headerImg || '/static/images/default-avatar.png';
  });

  const nickname = computed(() => {
    return userInfo.value?.nickName || '未设置昵称';
  });

  const userId = computed(() => {
    return userInfo.value?.uuid || '';
  });

  // Actions
  const setUserInfo = (info: UserInfo) => {
    userInfo.value = info;
    // 同时更新本地存储
    try {
      uni.setStorageSync('userInfo', info);
    } catch (error) {
      console.error('保存用户信息失败:', error);
    }
  };

  const updateUserInfo = (updates: Partial<UserInfo>) => {
    if (userInfo.value) {
      userInfo.value = { ...userInfo.value, ...updates };
      try {
        uni.setStorageSync('userInfo', userInfo.value);
      } catch (error) {
        console.error('更新用户信息失败:', error);
      }
    }
  };

  const setLoading = (loading: boolean) => {
    isLoading.value = loading;
  };

  const clearUserInfo = () => {
    userInfo.value = null;
    try {
      uni.removeStorageSync('token');
      uni.removeStorageSync('userInfo');
      uni.removeStorageSync('userId');
      uni.removeStorageSync('expiresAt');
    } catch (error) {
      console.error('清除用户信息失败:', error);
    }
  };

  const initUserInfo = () => {
    try {
      const localUserInfo = uni.getStorageSync('userInfo');
      if (localUserInfo && isLoggedIn.value) {
        userInfo.value = localUserInfo;
      } else if (!isLoggedIn.value) {
        // 如果 token 过期，清除用户信息
        clearUserInfo();
      }
    } catch (error) {
      console.error('初始化用户信息失败:', error);
    }
  };

  const logout = () => {
    clearUserInfo();
    // 跳转到登录页
    uni.reLaunch({
      url: '/pages/login/index',
    });
  };

  // 检查登录状态并自动登出过期用户
  const checkAuthStatus = () => {
    if (userInfo.value && !isLoggedIn.value) {
      logout();
    }
  };

  return {
    // 状态
    userInfo,
    isLoading,

    // 计算属性
    isLoggedIn,
    avatar,
    nickname,
    userId,

    // Actions
    setUserInfo,
    updateUserInfo,
    setLoading,
    clearUserInfo,
    initUserInfo,
    logout,
    checkAuthStatus,
  };
});
